//
//  PPSettingViewController.m
//  pickpic
//
//  Created by Jinxiao on 8/25/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPSettingViewController.h"
#import "PPLoginViewController.h"
#import "PPLoginNavigationController.h"
#import "PPSettingManager.h"
#import "PPLoginAndRegisterViewController.h"


#import "PPSettingModel.h"
#import "PPSettingPicCell.h"
#import "PPSettingCell.h"
#import "PPAccTypeCell.h"
#import "PPCacheCell.h"

#import "PPProfileSettingViewController.h"
#import "PPPasswordSettingViewController.h"
#import "PPFeedBackViewController.h"
#import "PPAboutViewController.h"

#define kSettingFont ([UIFont boldSystemFontOfSize:16])

@interface PPSettingViewController ()
@property (weak, nonatomic) IBOutlet UIView *line1;
@property (weak, nonatomic) IBOutlet UIView *line2;
@property (weak, nonatomic) IBOutlet UIView *line3;
@property (weak, nonatomic) IBOutlet UIView *line4;
@property (weak, nonatomic) IBOutlet UIView *line5;
@property (weak, nonatomic) IBOutlet UIView *line6;
@property (weak, nonatomic) IBOutlet UIView *line7;
@property (weak, nonatomic) IBOutlet UIView *line8;
@property (weak, nonatomic) IBOutlet UIView *line9;
@property (weak, nonatomic) IBOutlet UILabel *accountLabel;


@property (nonatomic,strong) NSArray *subtitles;

@property (nonatomic,copy) NSString *photoURL;
@property (nonatomic,copy) NSString *phone;

@property (nonatomic,copy) NSString *fileCachePath;
@property (nonatomic,copy) NSString *fileCacheSize;

@property (nonatomic,assign) BOOL isLoginType;
@end

@implementation PPSettingViewController

static NSString *const picCellID = @"SettingPicCell";
static NSString *const setCellID = @"SettingCell";
static NSString *const accCellID = @"AccTypeCell";
static NSString *const cacheCellID = @"CacheCell";

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
//    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
}

- (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
//     self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.title = @"设置";
    self.view.backgroundColor = WHITE;
    self.subtitles = @[@"个人资料",@"账号",@"清除缓存",@"关于",@"意见反馈",@"退出登录"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(popViewPreviousController)];
    
    self.navigationItem.leftBarButtonItem.tintColor = BLACK;
    
//    [_line1 addTopBorderWithColor:kLineColor andWidth:kLineWidth];
//    [_line2 addBottomBorderWithColor:kLineColor andWidth:kLineWidth];
//    [_line3 addBottomBorderWithColor:kLineColor andWidth:kLineWidth];
//    [_line4 addBottomBorderWithColor:kLineColor andWidth:kLineWidth];
//    [_line5 addBottomBorderWithColor:kLineColor andWidth:kLineWidth];
//
//    [_line6 addTopBorderWithColor:kLineColor andWidth:kLineWidth];
//    [_line7 addBottomBorderWithColor:kLineColor andWidth:kLineWidth];
//    [_line8 addBottomBorderWithColor:kLineColor andWidth:kLineWidth];
//    [_line9 addBottomBorderWithColor:kLineColor andWidth:kLineWidth];

    [self loadUserInfo];
    
    [self registerCell];
//    PPAccountProfiles *profile = [PPAccountManager sharedInstance].account.profiles;

//    _accountLabel.text = profile.name;
//
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        [PPSettingManager sharedInstance];
//    });
    
}
- (void)loadUserInfo{

    PPAccountProfiles *profile = [PPAccountManager sharedInstance].account.profiles;
    
    self.photoURL = profile.avatarURLString;
    
    
    DGAccount *acc = [DGAccount currentAccount];
    
    if (acc.phone.length > 0) {
        self.phone = acc.phone;
        
    }else{
        
        NSInteger souceType = [[PPUserAccount currentUser].source integerValue];
        if (souceType == 2) {
            self.phone = @"微信登录";
        }else if (souceType == 4){
        self.phone = @"qq登录";
        }else if(souceType == 8){
        self.phone = @"微博登录";
        }else{
        self.phone = @"第三方登录";
        }
        
        self.isLoginType = YES;
        
    }
    
    
    CGFloat size = [self getCacheSize];
    
    if (size >= 50) {
        size = 50.1;
    }
    
    self.fileCacheSize = [NSString stringWithFormat:@"%.2fM",size];
    
}
- (void)registerCell{

    self.tableView.separatorInset = UIEdgeInsetsMake(0, 14, 0, 0);
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PPSettingPicCell class]) bundle:nil] forCellReuseIdentifier:picCellID];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PPSettingCell class]) bundle:nil] forCellReuseIdentifier:setCellID];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PPAccTypeCell class]) bundle:nil] forCellReuseIdentifier:accCellID];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PPCacheCell class]) bundle:nil] forCellReuseIdentifier:cacheCellID];
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    if (indexPath.row == 0) {
        PPSettingPicCell *picCell = [self.tableView dequeueReusableCellWithIdentifier:picCellID];
        
        if (self.photoURL.length > 0) {
            [picCell.picImage sd_setImageWithURL:[NSURL URLWithString:self.photoURL]];
        }else{
             picCell.picImage.image = [UIImage imageNamed:@"person_normal"];
        }
        picCell.leftLabel.font = kSettingFont;
        return picCell;
        
    }else if (indexPath.row == 1){
        
        PPAccTypeCell *accCell = [self.tableView dequeueReusableCellWithIdentifier:accCellID];
    
        accCell.nickName.text = self.phone;
        accCell.leftLabel.font = kSettingFont;
        return accCell;
        
    
    }else if (indexPath.row == 2){
    
        PPCacheCell *cacheCell = [self.tableView dequeueReusableCellWithIdentifier:cacheCellID];
        cacheCell.cacheLabel.text = self.fileCacheSize;
        cacheCell.leftLabel.font = kSettingFont;
        return cacheCell;
        
    }else{
        PPSettingCell *picCell = [self.tableView dequeueReusableCellWithIdentifier:setCellID];
        picCell.leftLabel.text = self.subtitles[indexPath.row];
        picCell.leftLabel.font = kSettingFont;
        return picCell;
    }
    
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    
    switch(indexPath.row) {
        case 0: {
            PPProfileSettingViewController *profileVc = [[PPProfileSettingViewController alloc] init];
            [self.navigationController pushViewController:profileVc animated:YES];
//            switch(indexPath.row) {
//                case 3: {
//
//                    [MobClick event:@"164"];
//
//                    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
//                    [[SDImageCache sharedImageCache] clearDisk];
//                    [[SDImageCache sharedImageCache] clearMemory];
//                    [hud hide:YES];
//                    [self.navigationController.view toastMessage:@"缓存已清除"];
//
//                    break;
//                }
//            }
//            PPProfileSettingViewController *settingViewController = [[UIStoryboard storyboardWithName:@"Setting" bundle:nil] instantiateViewControllerWithIdentifier:@"PPSettingViewController"];

        }
            break;
            
        case 1:{
            if (self.isLoginType) { return; }
            PPPasswordSettingViewController *pwdVc = [[UIStoryboard storyboardWithName:@"Setting" bundle:nil] instantiateViewControllerWithIdentifier:@"PPPasswordSettingViewController"];
            [self.navigationController pushViewController:pwdVc animated:YES];
            
        }
            break;
        case 2:{
            [self cleanCache];
        }
            break;
        case 3:{
            
            
//            PPAboutViewController *aboutVc = [[UIStoryboard storyboardWithName:@"Setting" bundle:nil] instantiateViewControllerWithIdentifier:@"PPAboutViewController"];
//            [self.navigationController pushViewController:aboutVc animated:YES];
            
            
            
            
            PPAboutViewController *aboutVc = [[PPAboutViewController alloc] init];
            [self.navigationController pushViewController:aboutVc animated:YES];
        }
            break;
        case 4:{
//            PPFeedBackViewController *feedVc = [[PPFeedBackViewController alloc] init];
//            [self.navigationController pushViewController:feedVc animated:YES];
            
            PPFeedBackViewController *feedVc = [[UIStoryboard storyboardWithName:@"Setting" bundle:nil] instantiateViewControllerWithIdentifier:@"PPFeedBackViewController"];
            [self.navigationController pushViewController:feedVc animated:YES];
        }
            break;

        case 5: {

//            switch(indexPath.row) {
//                case 2: {
                    [MobClick event:@"165"];
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"确定退出登录?" preferredStyle:UIAlertControllerStyleAlert];
                    [alertController addAction:[UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                        [[PPAccountManager sharedInstance] logoutWithCompletion:^(BOOL success) {

                            if(success) {
//                                PPLoginViewController *loginViewController = [[UIStoryboard storyboardWithName:@"Login" bundle:nil] instantiateViewControllerWithIdentifier:@"PPLoginViewController"];
//                                PPLoginNavigationController *navigationController = [[PPLoginNavigationController alloc] initWithRootViewController:loginViewController];
//                                [[[UIApplication sharedApplication] delegate] window].rootViewController = navigationController;
                                
                                PPLoginAndRegisterViewController *loginRegister = [[PPLoginAndRegisterViewController alloc] init];
                                PPBaseNavigationViewController *navigationController = [[PPBaseNavigationViewController alloc] initWithRootViewController:loginRegister];
                                
                                [[[UIApplication sharedApplication] delegate] window].rootViewController = navigationController;
                            }
                        }];
                    }]];
                    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {

                    }]];
                    [self presentViewController:alertController animated:YES completion:nil];
                }
                    break;

//                default:
//                    break;
//            }
//        }

        default:
            break;
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (indexPath.section == 0 && indexPath.row == 1 && !(DGCurrentAccount.pickpicAccount))
//    {
//        return CGFLOAT_MIN;
//    }
//    return 46.f;
//}


//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 15;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return CGFLOAT_MIN;
//}
-(CGFloat) getCacheSize
{
    //获取文件管理器对象
    NSFileManager * fileManger = [NSFileManager defaultManager];
    
    //获取缓存沙盒路径
    NSArray *patchs = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
    
    // 获取Documents路径
    // [patchs objectAtIndex:0]
    NSString *documentsDirectory = [patchs objectAtIndex:0];
    
    //拼接缓存文件夹路径
    NSString * fileCachePath = [documentsDirectory stringByAppendingPathComponent:@""];
    
    //将缓存文件夹路径赋值给成员属性(后面删除缓存文件时需要用到)
    self.fileCachePath = fileCachePath;
    
    //通过缓存文件路径创建文件遍历器
    NSDirectoryEnumerator * fileEnumrator = [fileManger enumeratorAtPath:fileCachePath];
    
    //先定义一个缓存目录总大小的变量
    NSInteger fileTotalSize = 0;
    
    for (NSString * fileName in fileEnumrator)
    {
        //拼接文件全路径（注意：是文件）
        NSString * filePath = [fileCachePath stringByAppendingPathComponent:fileName];
        
        //获取文件属性
        NSDictionary * fileAttributes = [fileManger attributesOfItemAtPath:filePath error:nil];
        
        //根据文件属性判断是否是文件夹（如果是文件夹就跳过文件夹，不将文件夹大小累加到文件总大小）
        if ([fileAttributes[NSFileType] isEqualToString:NSFileTypeDirectory]) continue;
        
        //获取单个文件大小,并累加到总大小
        fileTotalSize += [fileAttributes[NSFileSize] integerValue];
    }
    
    //将字节大小转为MB，然后传出去
    return fileTotalSize/1000.0/1000;
}
//清除缓存
-(void)cleanCache
{
     [MobClick event:@"164"];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    //删除缓存目录下所有缓存文件
    [[NSFileManager defaultManager] removeItemAtPath:self.fileCachePath error:nil];
    
    self.fileCacheSize = @"0.00M";
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
//    [[SDImageCache sharedImageCache] clearDisk];
    
//    [[SDImageCache sharedImageCache] clearMemory];//可有可无
    [hud hide:YES];
    [self.navigationController.view toastMessage:@"缓存已清除"];
    
}
@end
